import 'dart:async';
import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/tools/locale_tool.dart';
import 'package:share_fit/app/tools/log_utils.dart';

class CountDownView extends StatefulWidget {
  const CountDownView({super.key});

  @override
  State<CountDownView> createState() => _CountDownViewState();
}

class _CountDownViewState extends State<CountDownView> {
  Timer? _timer;
  static const String count = '3';
  final ValueNotifier<String> _countDown = ValueNotifier(count);

  late AudioPlayer player;

  @override
  void initState() {
    super.initState();
    AudioCache.instance = AudioCache(prefix: '');
    player = AudioPlayer();
    player.onPlayerComplete.listen((event) {
      if (_countDown.value == '3') {
        _startTickTimer();
      }
    });
    _speak();
  }

  _startTickTimer() {
    logger.d('_startTickTimer');
    _timer = Timer.periodic(const Duration(milliseconds: 900), (timer) {
      if (_countDown.value == 'Go') {
        timer.cancel();
        Get.back(result: true);
      } else {
        int count = int.parse(_countDown.value);
        count--;
        if (count == 0) {
          _countDown.value = 'Go';
          _releasePlayer();
        } else {
          _countDown.value = '$count';
          _speak();
        }
      }

    });
  }

  _releasePlayer() async {
    logger.d('_releasePlayer');
    await player.stop();
    await player.dispose();
  }

  @override
  void dispose() {
    super.dispose();
    _countDown.dispose();
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.green.withOpacity(.2),
      child: Center(
        child: ValueListenableBuilder<String>(
          builder: (context, value, child) => Text(
            value,
            style: TextStyle(fontSize: 700.sp, color: Colors.white),
          ),
          valueListenable: _countDown,
        ),
      ),
    );
  }

  Future<void> _speak() async {
    String path = '';
    bool isEn = LocaleTool.locale=='en_US';
    if(_countDown.value=='3') {
      path = 'assets/sounds/num_3${isEn?'_en':''}.wav';
    } else if(_countDown.value=='2') {
      path = 'assets/sounds/num_2${isEn?'_en':''}.wav';
    } else if(_countDown.value=='1') {
      path = 'assets/sounds/num_1${isEn?'_en':''}.wav';
    }

    if(path == '') {
      return;
    }

    logger.d('path $path');
    await player.play(AssetSource(path));
  }
}
